package com.zr.redis.service;

import com.zr.redis.util.WatchDogLockUtil;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class WatchDogExampleService {

    private final WatchDogLockUtil watchDogLockUtil;

    @Autowired
    public WatchDogExampleService(WatchDogLockUtil watchDogLockUtil) {
        this.watchDogLockUtil = watchDogLockUtil;
    }

    /**
     * 示例1：使用看门狗模式处理长时间任务
     */
    public void processLongTimeTask(String taskId) {
        String lockKey = "long:task:lock:" + taskId;
        RLock lock = null;
        try {
            // 获取锁，不指定过期时间，自动启用看门狗
            lock = watchDogLockUtil.lockWithWatchDog(lockKey);

            // 执行长时间任务（超过30秒也没关系，看门狗会自动续期）
            System.out.println("开始处理长时间任务: " + taskId);

            // 模拟长时间业务处理（例如45秒）
            Thread.sleep(45000);

            System.out.println("长时间任务处理完成: " + taskId);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务处理被中断", e);
        } finally {
            // 释放锁
            watchDogLockUtil.unlock(lock);
        }
    }

    /**
     * 示例2：尝试获取看门狗锁
     */
    public void tryProcessTask(String taskId) {
        String lockKey = "long:task:lock:" + taskId;
        try {
            // 尝试获取锁，最多等待5秒，获取成功后不指定过期时间（启用看门狗）
            boolean locked = watchDogLockUtil.tryLockWithWatchDog(lockKey, 5, TimeUnit.SECONDS);
            if (locked) {
                try {
                    System.out.println("成功获取锁，开始处理任务: " + taskId);
                    // 模拟长时间任务
                    Thread.sleep(35000);
                    System.out.println("任务处理完成: " + taskId);
                } finally {
                    watchDogLockUtil.unlock(lockKey);
                }
            } else {
                System.out.println("获取锁失败，无法处理任务: " + taskId);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务处理被中断", e);
        }
    }
}

